﻿/*
	Class			Clock
	Package			utilities.Clock
	
	Description		Creates an object that dispatches an event every second, to redraw the clock time on a text field for a digital clock.
					Clock.getCurrentTime () returns a string to be used on the redraw (can implement different return value).
					
	History			1.01	6/18/07		Changed all uints to ints.
					1.00	5/29/07		Created
	
	To Do			Expand to allow different return strings. i.e. 5:01 PM,  5:01:32 PM,  17:01 etc...
*/

package pete.objects
{
	import pete.formats.StringFormat;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	
	public class Clock extends EventDispatcher
	{
		public static const TICK:String = "tick";
		
		public function Clock ()
		{
			drawClock ();
        	var ticker:Timer = new Timer (1000);
            ticker.addEventListener (TimerEvent.TIMER, everySecond);
            ticker.start ();
		}
		
		
		public function getCurrentTime ():String
		{
			var currentTime:Date     = new Date ();
			var hours:int            = currentTime.getHours ();
			var minutes:int          = currentTime.getMinutes ();
			var minutesString:String = StringFormat.doubleDigits (minutes);
			var ampm:String          = "PM";
			
			if (hours > 12)
			{
				hours = hours - 12;
			}
			else if (hours == 0)
			{
				ampm  = "AM";
				hours = 12;
			}
			else if (hours < 12)
			{
				ampm = "AM";
			}
			
			var timeString:String = hours + ":" + minutesString + " " + ampm;
			return timeString;
		}
		
		
		private function everySecond (eventObject:TimerEvent):void
		{
			drawClock ();
		}
		
		
		private function drawClock ()
		{
			var drawClockEvent:Event = new Event (Clock.TICK);
			dispatchEvent (drawClockEvent);
		}
	}
}